package org.summerframework.core.page;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.summerframework.core.base.result.DefaultResultCode;
import org.summerframework.core.exception.WebException;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.SuperBuilder;

import java.io.Serializable;
import java.util.List;

/**
 * 分页查询基础类
 *
 * @author 石超
 * @version 1.0.0
 */
@SuperBuilder
@Getter
@Setter
@AllArgsConstructor
public class PaginationQuery implements Serializable {

    private static final long serialVersionUID = 388550297405615227L;

    public PaginationQuery() {
    }

    /**
     * 当前页码
     */
    @Builder.Default
    @ApiModelProperty(value = "当前分页")
    private int pageIndex = 1;

    /**
     * 每页容量
     */
    @Builder.Default
    @ApiModelProperty(value = "分页数量")
    private int pageSize = 20;

    /**
     * 是否分页
     */
    @Builder.Default
    @ApiModelProperty(value = "是否分页, false查询全部", example = "true")
    private Boolean isPagination = true;

    @JsonIgnore
    @Builder.Default
    private boolean isConstruct = false;

    /**
     * 设置当前页
     *
     * @param pageIndex 当前页
     */
    public void setPageIndex(int pageIndex) {
        if (pageIndex <= 0) {
            throw new WebException(DefaultResultCode.ILLEGAL_ARGUMENT);
        }
        this.pageIndex = pageIndex;
    }

    /**
     * mysql startRow begin 0!
     */
    public int getStartRow() {
        return pageSize * (pageIndex - 1);
    }

    /**
     * 修复in时, list为空数组报错的问题,
     * 传空数组理论上是无法查出数据的, 添加一个null即可
     *
     * @param list 原数组
     * @param <T>  泛型
     * @return 修复后的数组
     */
    public static <T> List<T> repairIn(List<T> list) {
        if (list != null && list.isEmpty()) {
            list.add(null);
        }

        return list;
    }
}
